package cn.desk.commons.interceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.desk.commons.util.SessionProvider;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class SessionProviderInterceptor extends AbstractInterceptor {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger logger=LoggerFactory.getLogger(SessionProviderInterceptor.class);
	private List<SessionProvider> sessionProviders;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		logger.debug("intercept start");
		try{
			HttpSession session= ServletActionContext.getRequest().getSession();
			if(session.isNew()){
				if(logger.isInfoEnabled()){
					logger.info("new Session.SessionID "+session.getId());
				}
				if(sessionProviders!=null){
					for(SessionProvider sp:sessionProviders){
						Map<String ,Object> map=sp.provider();
						for(Entry<String, Object> ent:map.entrySet()){
							session.setAttribute(ent.getKey(), ent.getValue());
							if(logger.isInfoEnabled()){
								logger.info("session->key:"+ent.getKey() +"=value:"+ent.getValue());
							}
						}
					}
				}
			}
			return invocation.invoke();
		}finally{
			logger.debug("intercept end");
		}
		
	}

	public List<SessionProvider> getSessionProviders() {
		return sessionProviders;
	}

	public void setSessionProviders(List<SessionProvider> sessionProviders) {
		this.sessionProviders = sessionProviders;
	}
	
	public void setSessionProviders(SessionProvider sessionProvider) {
		if(sessionProviders==null){
			sessionProviders=new ArrayList<SessionProvider>();
		}
		sessionProviders.add(sessionProvider);
	}
}
